In [132]:
import datashader as ds
import datashader.transfer_functions as tf
import datashader.glyphs
from datashader import reductions
from datashader.core import bypixel
from datashader.utils import lnglat_to_meters as webm, export_image
from datashader.colors import colormap_select, Greys9, viridis, inferno
import copy
import math


from pyproj import Proj, transform
import numpy as np
import pandas as pd
import urllib
import json
import datetime
import colorlover as cl

import plotly.offline as py
import plotly.graph_objs as go
from plotly import tools

#from shapely.geometry import Point, Polygon, shape
# In order to get shapley, you'll need to run [pip install shapely.geometry] from your terminal

from functools import partial

from IPython.display import GeoJSON

py.init_notebook_mode()

For module 2 we'll be looking at techniques for dealing with big data. In particular binning strategies and the datashader library (which possibly proves we'll never need to bin large data for visualization ever again.)

To demonstrate these concepts we'll be looking at the PLUTO dataset put out by New York City's department of city planning. PLUTO contains data about every tax lot in New York City.

PLUTO data can be downloaded from here. Unzip them to the same directory as this notebook, and you should be able to read them in using this (or very similar) code. Also take note of the data dictionary, it'll come in handy for this assignment.

In [3]:
# Code to read in v17, column names have been updated (without upper case letters) for v18

# bk = pd.read_csv('PLUTO17v1.1/BK2017V11.csv')
# bx = pd.read_csv('PLUTO17v1.1/BX2017V11.csv')
# mn = pd.read_csv('PLUTO17v1.1/MN2017V11.csv')
# qn = pd.read_csv('PLUTO17v1.1/QN2017V11.csv')
# si = pd.read_csv('PLUTO17v1.1/SI2017V11.csv')

# ny = pd.concat([bk, bx, mn, qn, si], ignore_index=True)

ny = pd.read_csv('pluto_20v1.csv')



# Getting rid of some outliers
ny = ny[(ny['yearbuilt'] > 1850) & (ny['yearbuilt'] < 2020) & (ny['numfloors'] != 0)]
C:\Users\robbj\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py:3057: DtypeWarning:

Columns (17,18,20,22) have mixed types. Specify dtype option on import or set low_memory=False.

I'll also do some prep for the geographic component of this data, which we'll be relying on for datashader.

You're not required to know how I'm retrieving the lattitude and longitude here, but for those interested: this dataset uses a flat x-y projection (assuming for a small enough area that the world is flat for easier calculations), and this needs to be projected back to traditional lattitude and longitude.

In [4]:
# wgs84 = Proj("+proj=longlat +ellps=GRS80 +datum=NAD83 +no_defs")
# nyli = Proj("+proj=lcc +lat_1=40.66666666666666 +lat_2=41.03333333333333 +lat_0=40.16666666666666 +lon_0=-74 +x_0=300000 +y_0=0 +ellps=GRS80 +datum=NAD83 +to_meter=0.3048006096012192 +no_defs")
# ny['xcoord'] = 0.3048*ny['xcoord']
# ny['ycoord'] = 0.3048*ny['ycoord']
# ny['lon'], ny['lat'] = transform(nyli, wgs84, ny['xcoord'].values, ny['ycoord'].values)

# ny = ny[(ny['lon'] < -60) & (ny['lon'] > -100) & (ny['lat'] < 60) & (ny['lat'] > 20)]

#Defining some helper functions for DataShader
background = "black"
export = partial(export_image, background = background, export_path="export")
cm = partial(colormap_select, reverse=(background!="black"))

Part 1: Binning and Aggregation¶

Binning is a common strategy for visualizing large datasets. Binning is inherent to a few types of visualizations, such as histograms and 2D histograms (also check out their close relatives: 2D density plots and the more general form: heatmaps.

While these visualization types explicitly include binning, any type of visualization used with aggregated data can be looked at in the same way. For example, lets say we wanted to look at building construction over time. This would be best viewed as a line graph, but we can still think of our results as being binned by year:

In [5]:
trace = go.Scatter(
    # I'm choosing BBL here because I know it's a unique key.
    x = ny.groupby('yearbuilt').count()['bbl'].index,
    y = ny.groupby('yearbuilt').count()['bbl']
)

layout = go.Layout(
    xaxis = dict(title = 'Year Built'),
    yaxis = dict(title = 'Number of Lots Built')
)

fig = go.FigureWidget(data = [trace], layout = layout)

fig

Something looks off... You're going to have to deal with this imperfect data to answer this first question.

But first: some notes on pandas. Pandas dataframes are a different beast than R dataframes, here are some tips to help you get up to speed:


Hello all, here are some pandas tips to help you guys through this homework:

Indexing and Selecting: .loc and .iloc are the analogs for base R subsetting, or filter() in dplyr

Group By: This is the pandas analog to group_by() and the appended function the analog to summarize(). Try out a few examples of this, and display the results in Jupyter. Take note of what's happening to the indexes, you'll notice that they'll become hierarchical. I personally find this more of a burden than a help, and this sort of hierarchical indexing leads to a fundamentally different experience compared to R dataframes. Once you perform an aggregation, try running the resulting hierarchical datafrome through a reset_index().

Reset_index: I personally find the hierarchical indexes more of a burden than a help, and this sort of hierarchical indexing leads to a fundamentally different experience compared to R dataframes. reset_index() is a way of restoring a dataframe to a flatter index style. Grouping is where you'll notice it the most, but it's also useful when you filter data, and in a few other split-apply-combine workflows. With pandas indexes are more meaningful, so use this if you start getting unexpected results.

Indexes are more important in Pandas than in R. If you delve deeper into the using python for data science, you'll begin to see the benefits in many places (despite the personal gripes I highlighted above.) One place these indexes come in handy is with time series data. The pandas docs have a huge section on datetime indexing. In particular, check out resample, which provides time series specific aggregation.

Merging, joining, and concatenation: There's some overlap between these different types of merges, so use this as your guide. Concat is a single function that replaces cbind and rbind in R, and the results are driven by the indexes. Read through these examples to get a feel on how these are performed, but you will have to manage your indexes when you're using these functions. Merges are fairly similar to merges in R, similarly mapping to SQL joins.

Apply: This is explained in the "group by" section linked above. These are your analogs to the plyr library in R. Take note of the lambda syntax used here, these are anonymous functions in python. Rather than predefining a custom function, you can just define it inline using lambda.

Browse through the other sections for some other specifics, in particular reshaping and categorical data (pandas' answer to factors.) Pandas can take a while to get used to, but it is a pretty strong framework that makes more advanced functions easier once you get used to it. Rolling functions for example follow logically from the apply workflow (and led to the best google results ever when I first tried to find this out and googled "pandas rolling")

Google Wes Mckinney's book "Python for Data Analysis," which is a cookbook style intro to pandas. It's an O'Reilly book that should be pretty available out there.


Question¶

After a few building collapses, the City of New York is going to begin investigating older buildings for safety. The city is particularly worried about buildings that were unusually tall when they were built, since best-practices for safety hadn’t yet been determined. Create a graph that shows how many buildings of a certain number of floors were built in each year (note: you may want to use a log scale for the number of buildings). Find a strategy to bin buildings (It should be clear 20-29-story buildings, 30-39-story buildings, and 40-49-story buildings were first built in large numbers, but does it make sense to continue in this way as you get taller?)

In [236]:
# create a new dataframe with only the variables of interest for this problem
df_q1 = ny[['yearbuilt', 'bbl', 'numfloors']]

## bin the floors into groups (this was an iterative process)
# set breakpoints
bin_floors = [1,2,5,15,25,50,200]

# apply the cut and set labels for each bin grouping
cut = pd.cut(df_q1['numfloors'], bin_floors, labels=['1-2','3-5','6-15','16-25','26-50','over 50'])

# insert the cut back into the dataframe
df_q1.insert(3, "cut_floors", cut, True)

# group year by decade 
decade = (np.ceil(df_q1['yearbuilt']/10) *10).astype(int)
df_q1.insert(4,'decadebuilt', decade, True)

# group data by decade and floors to get a tally 
grouped = df_q1.groupby(['decadebuilt','cut_floors'],as_index=False)
group_agg = grouped.aggregate(np.size)
group_agg = group_agg[['decadebuilt','cut_floors', 'numfloors']]

# pivot the table to get into right format for matplotlib stacked barchart
piv = group_agg.pivot(index='decadebuilt', columns='cut_floors',values='numfloors')

# make the plot
piv.loc[:,['1-2','3-5','6-15','16-25','26-50','over 50']].plot.bar(stacked=True,log=True, figsize=(10,10))
plt.xlabel('Decade Built')
plt.ylabel('Number of constructions')
Out[236]:
Text(0, 0.5, 'Number of constructions')

Part 2: Datashader¶

Datashader is a library from Anaconda that does away with the need for binning data. It takes in all of your datapoints, and based on the canvas and range returns a pixel-by-pixel calculations to come up with the best representation of the data. In short, this completely eliminates the need for binning your data.

As an example, lets continue with our question above and look at a 2D histogram of YearBuilt vs NumFloors:

In [28]:
yearbins = 200
floorbins = 200

yearBuiltCut = pd.cut(ny['yearbuilt'], np.linspace(ny['yearbuilt'].min(), ny['yearbuilt'].max(), yearbins))
numFloorsCut = pd.cut(ny['numfloors'], np.logspace(1, np.log(ny['numfloors'].max()), floorbins))

xlabels = np.floor(np.linspace(ny['yearbuilt'].min(), ny['yearbuilt'].max(), yearbins))
ylabels = np.floor(np.logspace(1, np.log(ny['numfloors'].max()), floorbins))

fig = go.FigureWidget(
    data = [
        go.Heatmap(z = ny.groupby([numFloorsCut, yearBuiltCut])['bbl'].count().unstack().fillna(0).values,
              colorscale = 'Greens', x = xlabels, y = ylabels)
    ]
)

fig

This shows us the distribution, but it's subject to some biases discussed in the Anaconda notebook Plotting Perils.

Here is what the same plot would look like in datashader:

In [52]:
cvs = ds.Canvas(800, 500, x_range = (ny['yearbuilt'].min(), ny['yearbuilt'].max()), 
                                y_range = (ny['numfloors'].min(), ny['numfloors'].max()))
agg = cvs.points(ny, 'yearbuilt', 'numfloors')
view = tf.shade(agg, cmap = cm(Greys9), how='log')
export(tf.spread(view, px=2), 'yearvsnumfloors')
Out[52]:

That's technically just a scatterplot, but the points are smartly placed and colored to mimic what one gets in a heatmap. Based on the pixel size, it will either display individual points, or will color the points of denser regions.

Datashader really shines when looking at geographic information. Here are the latitudes and longitudes of our dataset plotted out, giving us a map of the city colored by density of structures:

In [53]:
NewYorkCity   = (( 913164.0,  1067279.0), (120966.0, 272275.0))
cvs = ds.Canvas(700, 700, *NewYorkCity)
agg = cvs.points(ny, 'xcoord', 'ycoord')
view = tf.shade(agg, cmap = cm(inferno), how='log')
export(tf.spread(view, px=2), 'firery')
Out[53]:

Interestingly, since we're looking at structures, the large buildings of Manhattan show up as less dense on the map. The densest areas measured by number of lots would be single or multi family townhomes.

Unfortunately, Datashader doesn't have the best documentation. Browse through the examples from their github repo. I would focus on the visualization pipeline and the US Census Example for the question below. Feel free to use my samples as templates as well when you work on this problem.

Question¶

You work for a real estate developer and are researching underbuilt areas of the city. After looking in the Pluto data dictionary, you've discovered that all tax assessments consist of two parts: The assessment of the land and assessment of the structure. You reason that there should be a correlation between these two values: more valuable land will have more valuable structures on them (more valuable in this case refers not just to a mansion vs a bungalow, but an apartment tower vs a single family home). Deviations from the norm could represent underbuilt or overbuilt areas of the city. You also recently read a really cool blog post about bivariate choropleth maps, and think the technique could be used for this problem.

Datashader is really cool, but it's not that great at labeling your visualization. Don't worry about providing a legend, but provide a quick explanation as to which areas of the city are overbuilt, which areas are underbuilt, and which areas are built in a way that's properly correlated with their land value.

In [99]:
# find the variables that describe land assessment and tax lot assessment values (referencing PLLUTO dictionary)
# variables of interest are assessland and assesstot

# Approach: Find quantile(n=3) for each of the two variables
# label v1 with ABC and v2 with 123
# combine into one variable 
# plot with datashader

# create new dataframe with variables of interest
df_q2 = ny[['xcoord','ycoord','assesstot', 'assessland']]

# # find quantiles of assesstot and put in df
# A < B < C
cut1 = pd.qcut(df_q2['assesstot'],3,labels=['A','B','C'])
df_q2.insert(4,'assesstot_cut', cut1, True)

# find quantiles of assessland
# 1 < 2 < 3
cut2 = pd.qcut(df_q2['assessland'],3,labels=['1','2','3'])
df_q2.insert(5,'assessland_cut', cut2, True)

# combine cut assessments into one variable
com =df_q2['assesstot_cut'].str.cat(df_q2['assessland_cut'])
df_q2.insert(6, "assess2",com,True)

# change variable to categorical (required by datashader)
df_q2['assess2'] = pd.Categorical(df_q2['assess2'])
df_q2.head()
C:\Users\robbj\Anaconda3\lib\site-packages\ipykernel_launcher.py:23: SettingWithCopyWarning:


A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

Out[99]:
xcoord ycoord assesstot assessland assesstot_cut assessland_cut assess2
0 982211.0 171707.0 350550.0 146250.0 C 3 C3
1 1026895.0 225880.0 78900.0 12240.0 C 2 C2
2 1004527.0 177269.0 34380.0 18120.0 A 3 A3
3 1004804.0 166580.0 24600.0 7680.0 A 1 A1
4 1004784.0 166579.0 29760.0 8160.0 A 1 A1
5 1004764.0 166577.0 29760.0 8160.0 A 1 A1
6 1004743.0 166575.0 29760.0 8160.0 A 1 A1
7 1004756.0 166668.0 27300.0 7500.0 A 1 A1
8 1001637.0 152477.0 25380.0 11160.0 A 1 A1
9 1005003.0 166817.0 33900.0 9180.0 A 1 A1
10 1017268.0 204027.0 41940.0 13800.0 B 2 B2
11 1022705.0 257574.0 37380.0 8760.0 A 1 A1
12 1005520.0 167099.0 35460.0 8580.0 A 1 A1
13 1026850.0 263788.0 24840.0 8100.0 A 1 A1
14 1005791.0 167010.0 34020.0 13620.0 A 2 A2
15 1006221.0 179865.0 113400.0 9450.0 C 1 C1
16 987197.0 182481.0 139860.0 32940.0 C 3 C3
18 1025439.0 262789.0 25200.0 7200.0 A 1 A1
19 1006342.0 166916.0 47760.0 10080.0 B 1 B1
20 1006333.0 167020.0 47760.0 12300.0 B 2 B2
21 1057054.0 177999.0 36660.0 8220.0 A 1 A1
22 1002660.0 165784.0 35280.0 8040.0 A 1 A1
23 1002659.0 165808.0 36480.0 8520.0 A 1 A1
24 956707.0 156166.0 61020.0 16380.0 B 2 B2
25 1014235.0 182225.0 42420.0 11640.0 B 2 B2
26 1006085.0 153868.0 41340.0 9420.0 B 1 B1
27 1001734.0 166953.0 46020.0 14580.0 B 2 B2
28 956583.0 156091.0 95580.0 33000.0 C 3 C3
29 956638.0 156116.0 44760.0 16140.0 B 2 B2
30 1010118.0 165588.0 32640.0 7980.0 A 1 A1
... ... ... ... ... ... ... ...
859142 1002178.0 171659.0 35400.0 12660.0 A 2 A2
859143 1031912.0 250329.0 37080.0 9720.0 A 1 A1
859144 1002632.0 166284.0 32820.0 9180.0 A 1 A1
859145 1002817.0 167070.0 34860.0 9180.0 A 1 A1
859146 1002856.0 167073.0 34860.0 9120.0 A 1 A1
859147 999365.0 227898.0 647100.0 181800.0 C 3 C3
859148 997346.0 221810.0 1129500.0 180000.0 C 3 C3
859149 998648.0 227711.0 8082450.0 1125000.0 C 3 C3
859150 1000014.0 230996.0 137280.0 42120.0 C 3 C3
859151 1002898.0 167077.0 35760.0 10740.0 A 1 A1
859152 1002920.0 167076.0 37620.0 7980.0 A 1 A1
859153 984724.0 180718.0 331920.0 104400.0 C 3 C3
859154 994350.0 232889.0 1036350.0 67500.0 C 3 C3
859155 982533.0 159583.0 78300.0 18720.0 C 3 C3
859156 986781.0 159050.0 94740.0 19200.0 C 3 C3
859157 1003230.0 166678.0 36480.0 10020.0 A 1 A1
859158 1003123.0 166750.0 26160.0 7560.0 A 1 A1
859159 1003480.0 166823.0 245700.0 42300.0 C 3 C3
859160 1019280.0 186070.0 40560.0 15780.0 B 2 B2
859161 1007254.0 179508.0 130680.0 14850.0 C 2 C2
859162 1014646.0 195467.0 398250.0 8100.0 C 1 C1
859163 992913.0 154778.0 56880.0 9960.0 B 1 B1
859164 1020646.0 186673.0 34860.0 16740.0 A 2 A2
859165 1004824.0 166582.0 29760.0 8160.0 A 1 A1
859166 1063525.0 206474.0 50280.0 18120.0 B 3 B3
859167 1022358.0 261858.0 431100.0 9450.0 C 1 C1
859168 1063503.0 206551.0 40200.0 15120.0 B 2 B2
859169 997519.0 204933.0 134940.0 20940.0 C 3 C3
859170 999843.0 237139.0 138060.0 37200.0 C 3 C3
859171 998733.0 239420.0 194400.0 43980.0 C 3 C3

811684 rows × 7 columns

In [222]:
# plot with Datashader

NewYorkCity   = (( 913164.0,  1067279.0), (120966.0, 272275.0))

#color key 
color_key = {'C1': '#c8b35a', 'C2': '#5a9178', 'C3': '#2a5a5b', 
             'B1': '#b8d6be', 'B2': '#90b2b3', 'B3': '#567994', 
             'A1': '#e8e8e8', 'A2': '#b5c0da', 'A3': '#c85a5a'}

#set canvas
cvs = ds.Canvas(700, 700, *NewYorkCity)

# set aggregation
agg = cvs.points(df_q2, 'xcoord', 'ycoord', ds.count_cat('assess2'))

# set view
view = tf.shade(agg, color_key=color_key)

# 
export(tf.spread(view, px=1), 'chloropleth_nyc')

# The pixels in red have a value of 'A3' which means the land is assessed in the upper third quantile but the tax lot is assessed in the lower third 
# These underbuilt areas are in the eastern part of brooklyn 
# The pixels with C1 are colored in yellow  and represent over built areas. There appear to be more overbuilt than underbuilt areas, especially in western and nothern Brooklyn. The highest concentrations are in the Ridgewood/Bushwick area.
Out[222]: